﻿#include "cdboracleoper.h"

#include <QDebug>
#include <QSqlError>

#include "cdbtableinfomgr.h"

CDbOracleOper::CDbOracleOper(const QString &sConnectInfo, const QString &sConnectName)
    : CDbBaseOper(sConnectInfo)
{
    QString str = sConnectName;
    qDebug() << sConnectName;
    if(str.isEmpty())
    {
        str = "Oracle : " + sConnectInfo.left(5);
    }
    if (QSqlDatabase::contains(str))
    {
        m_db = QSqlDatabase::database(str);
    }
    else
    {
        m_db = QSqlDatabase::addDatabase("QOCI", str);
    }
}

CDbOracleOper::CDbOracleOper(const CDataBaseConfig &cDbCfg)
    : CDbBaseOper(cDbCfg)
{
    QString str = cDbCfg.sConnectName;
    qDebug() << cDbCfg.sConnectName;
    if(str.isEmpty())
    {
        str = "Oracle : Oper";
    }
    if(QSqlDatabase::contains(str))
    {
        m_db = QSqlDatabase::database(str);
    }
    else
    {
        m_db = QSqlDatabase::addDatabase("QOCI", str);
    }
}

CDbOracleOper::~CDbOracleOper()
{
}

//连接数据库
bool CDbOracleOper::open()
{
    bool bRet = false;
    m_db.setHostName(m_dbCfg.sIP);
    m_db.setDatabaseName(m_dbCfg.sName);
    m_db.setUserName(m_dbCfg.sUserName);
    m_db.setPassword(m_dbCfg.sPassWord);
    m_db.setPort(m_dbCfg.nPort);
    if (m_db.open())
    {
        bRet = true;
    }
    return bRet;
}

//判断数据库是否连接
bool CDbOracleOper::isOpen()
{
    QString sSql = "select 1 from dual";
    QSqlQuery query(m_db);
    bool bReturn = query.exec(sSql);
    return bReturn;
}

//初始化数据库表信息
void CDbOracleOper::initTableInfo(CDbTableInfoMgr *pMgr)
{
    if(nullptr == pMgr) return;
    QString sSqlStr = "";
    sSqlStr = "select *from " + getTableName(pMgr) + " where 1 = 0";
    QSqlQuery query(m_db);
    query.prepare(sSqlStr);
    if(false == query.exec())
    {
        QString err = query.lastError().text();
        writeLog(QObject::tr("[GetRecordInfo]init table failed, SQL:%1").arg(sSqlStr), CLogBase::enLevelError);
        writeLog(QObject::tr("[GetRecordInfo]init table failed, error msg:%1").arg(err), CLogBase::enLevelError);
        pMgr->m_bSqlOperIsOk = false;
    }
    else
    {
        pMgr->m_mapFieldValue.clear();
        QSqlRecord record = query.record();
        for(int i=0; i<record.count(); ++i)
        {
            QString sField = record.fieldName(i);
            QVariant var = record.value(i);
            pMgr->m_mapFieldValue.insert(sField, var);
        }
        pMgr->m_bSqlOperIsOk = true;
    }
}
